﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using System.Security.Principal;

using Happy.ExtentionMethods;

namespace Happy.Security.Principal
{
    /// <summary>
    /// 主体。
    /// </summary>
    public sealed class HappyPrincipal : IPrincipal
    {
        private readonly IEnumerable<string> _roles;

        /// <summary>
        /// 构造方法。
        /// </summary>
        public HappyPrincipal(HappyIdentity identity, IEnumerable<string> roles = null)
        {
            identity.MustNotNull("identity");

            this.Identity = identity;
            _roles = roles;
        }

        /// <summary>
        /// 未通过认证的凭证。
        /// </summary>
        public static HappyPrincipal UnAuthenticatedPrincipal { get; private set; }

        static HappyPrincipal()
        {
            UnAuthenticatedPrincipal = new HappyPrincipal(HappyIdentity.UnAuthenticatedIdentity);
        }

        /// <summary>
        /// 标识。
        /// </summary>
        public IIdentity Identity { get; private set; }

        /// <summary>
        /// 是否属于指定的角色。
        /// </summary>
        public bool IsInRole(string role)
        {
            if (_roles == null)
            {
                return false;
            }

            return _roles.Any(x => x.ToLower() == role.ToLower());
        }
    }
}
